package cn.zhaoyun.service.impl;

import cn.zhaoyun.dao.EmpDao;
import cn.zhaoyun.entity.Emp;
import cn.zhaoyun.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

// 代码的形式使用缓存(非注解)
// @Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
public class EmpServiceImpl02 implements EmpService {
    @Autowired
    private EmpDao dao;

    // 注入缓存管理器
    @Autowired
    private RedisCacheManager redisCacheManager;

    @Override
    @Transactional(readOnly = true)
    public Emp findById(long id) {
        System.out.println("service执行操作, 根据id查询员工: " + id);

        // 获取某个缓存组件
        Cache cache = redisCacheManager.getCache("emps");
        
        // cache.get(id).get();
        Emp emp = dao.selectById(id);

        // 向缓存组件中存入数据
        cache.put(id, emp);
        return emp;
    }

    @Override
    public Emp update(Emp emp) {
        System.out.println("service执行操作, 更新员工信息: " + emp);
        dao.update(emp);
        return emp;
    }

    @Override
    public void delete(long id) {
        System.out.println("service执行操作, 删除员工: " + id);
        // dao.deleteById(id);
    }

    @Override
    public Emp findByName(String name) {
        System.out.println("service执行操作, 根据姓名查询员工: " + name);
        return dao.selectByName(name);
    }
}
